export default {
  namespaced: true,
  state: {
    // num: uni.getStorageSync('num') || 0
    num: 0,
    cart: [],
    address: {}
  },
  mutations: {
    setNum(state) {
      state.num++
      // uni.setStorageSync('num', state.num)
    },
    addToCart(state, val) {
      // 添加时，如果存在相应商品，要做goods_count++  不存在，push
      const findItem = state.cart.find(item => item.goods_id === val.goods_id)
      if (findItem) {
        findItem.goods_count++
      } else {
        state.cart.push(val)
      }
      console.log(state.cart);
    },
    setStatus(state, id) {
      const findItem = state.cart.find(item => item.goods_id === id)
      if (findItem) {
        findItem.goods_status = !findItem.goods_status
      }
    },
    // 修改商品数量
    setCount(state, obj) {
      // 找出要修改的商品
      const findItem = state.cart.find(item => item.goods_id === obj.goods_id)
      if (findItem) {
        findItem.goods_count = obj.goods_count
      }
    },
    // 删除商品
    delGoods(state, id) {
      // [{id:1},{id:2},{id:3}]   2
      state.cart = state.cart.filter(item => item.goods_id !== id)
    },
    // 修改收货地址
    setAddress(state, obj) {
      state.address = obj
    },
    // 全选与取消全选
    selectAll(state, bol) {
      state.cart.forEach(item => {
        item.goods_status = bol
      })
    },
    // 删除已购买商品
    delHasPay(state) {
      state.cart = state.cart.filter(item => item.goods_status === false)
    }

  },
  actions: {},
  getters: {
    total(state) {
      return state.cart.reduce((pre, item) => pre + item.goods_count, 0)
    },
    newTotal(state) {
      const newArr = state.cart.filter(item => item.goods_status)
      return newArr.reduce((pre, item) => pre + item.goods_count, 0)
    },
    totalMoney(state) {
      // 总价格：数量*单价总合
      const newArr = state.cart.filter(item => item.goods_status)
      return newArr.reduce((prev, item) => prev + item.goods_count * item.goods_price, 0)
    },
    // 是否处于全选状态
    isAll(state) {
      // 所有项都是选中状态就是全选，只要有一个项不是选中就是非全选
      // some:只要有一个项满足条件就是true  
      // every:所有项都满足条件才是true
      return state.cart.every(item => item.goods_status)
    }
  }
}